<template>
  <div class="role-create-container">
    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">新增角色</span>
          <div class="actions">
            <el-button @click="handleBack">
              <IconifyIconOffline icon="ep:back" class="mr-1" />
              返回
            </el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="role-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">
            <IconifyIconOffline icon="ep:info-filled" />
            基本信息
          </div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="角色名称" prop="name">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入角色名称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="角色编码" prop="code">
                <el-input
                  v-model="formData.code"
                  placeholder="请输入角色编码（英文字母、数字、下划线）"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="formData.status">
                  <el-radio value="enabled">启用</el-radio>
                  <el-radio value="disabled">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number
                  v-model="formData.sort"
                  :min="1"
                  :max="999"
                  placeholder="请输入排序值"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="角色描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入角色描述"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 权限配置 -->
        <div class="form-section">
          <div class="section-title">
            <IconifyIconOffline icon="ep:key" />
            权限配置
          </div>

          <div class="permission-config">
            <div class="config-actions">
              <el-button size="small" @click="handleExpandAll">
                <IconifyIconOffline icon="ep:plus" class="mr-1" />
                展开全部
              </el-button>
              <el-button size="small" @click="handleCollapseAll">
                <IconifyIconOffline icon="ep:minus" class="mr-1" />
                收起全部
              </el-button>
              <el-button size="small" @click="handleCheckAll">
                <IconifyIconOffline icon="ep:select" class="mr-1" />
                全选
              </el-button>
              <el-button size="small" @click="handleUncheckAll">
                <IconifyIconOffline icon="ep:close" class="mr-1" />
                取消全选
              </el-button>
            </div>

            <el-tree
              ref="permissionTreeRef"
              :data="permissionTree"
              :props="treeProps"
              show-checkbox
              node-key="id"
              :default-expand-all="false"
              :check-strictly="false"
              class="permission-tree"
              @check="handlePermissionCheck"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <IconifyIconOffline
                    :icon="data.icon || 'ep:folder'"
                    class="node-icon"
                  />
                  <span class="node-label">{{ node.label }}</span>
                  <el-tag v-if="data.type" size="small" class="node-type">
                    {{ getPermissionTypeText(data.type) }}
                  </el-tag>
                  <span v-if="data.description" class="node-desc">{{
                    data.description
                  }}</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>

        <!-- 其他设置 -->
        <div class="form-section">
          <div class="section-title">
            <IconifyIconOffline icon="ep:setting" />
            其他设置
          </div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据权限">
                <el-select
                  v-model="formData.dataScope"
                  placeholder="选择数据权限范围"
                  style="width: 100%"
                >
                  <el-option label="全部数据" value="all" />
                  <el-option label="本部门数据" value="dept" />
                  <el-option
                    label="本部门及下级部门数据"
                    value="dept_and_child"
                  />
                  <el-option label="仅本人数据" value="self" />
                  <el-option label="自定义数据" value="custom" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="菜单权限">
                <el-select
                  v-model="formData.menuCheckStrictly"
                  placeholder="选择菜单权限模式"
                  style="width: 100%"
                >
                  <el-option label="父子联动" value="false" />
                  <el-option label="父子独立" value="true" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button size="large" @click="handleBack">取消</el-button>
          <el-button
            type="primary"
            size="large"
            :loading="submitting"
            @click="handleSubmit"
          >
            保存
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, type ElTree, type FormInstance } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";

const router = useRouter();

// 表单引用
const formRef = ref<FormInstance>();
const permissionTreeRef = ref<InstanceType<typeof ElTree>>();

// 状态
const submitting = ref(false);

// 表单数据
const formData = reactive({
  name: "",
  code: "",
  description: "",
  status: "enabled",
  sort: 1,
  dataScope: "all",
  menuCheckStrictly: "false",
  remark: "",
  permissions: []
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "角色名称长度在 2 到 50 个字符",
      trigger: "blur"
    }
  ],
  code: [
    { required: true, message: "请输入角色编码", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "角色编码长度在 2 到 50 个字符",
      trigger: "blur"
    },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "角色编码只能包含字母、数字和下划线",
      trigger: "blur"
    }
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  sort: [
    { required: true, message: "请输入排序值", trigger: "blur" },
    {
      type: "number",
      min: 1,
      max: 999,
      message: "排序值必须在 1 到 999 之间",
      trigger: "blur"
    }
  ]
};

// 权限树配置
const treeProps = {
  children: "children",
  label: "name"
};

// 权限树数据
const permissionTree = ref([
  {
    id: 1,
    name: "系统管理",
    icon: "ep:setting",
    type: "menu",
    description: "系统基础管理功能",
    children: [
      {
        id: 11,
        name: "用户管理",
        icon: "ep:user",
        type: "menu",
        description: "用户信息管理",
        children: [
          {
            id: 111,
            name: "用户查询",
            type: "button",
            description: "查看用户列表"
          },
          {
            id: 112,
            name: "用户新增",
            type: "button",
            description: "新增用户"
          },
          {
            id: 113,
            name: "用户修改",
            type: "button",
            description: "修改用户信息"
          },
          {
            id: 114,
            name: "用户删除",
            type: "button",
            description: "删除用户"
          },
          {
            id: 115,
            name: "重置密码",
            type: "button",
            description: "重置用户密码"
          }
        ]
      },
      {
        id: 12,
        name: "角色管理",
        icon: "ep:avatar",
        type: "menu",
        description: "角色权限管理",
        children: [
          {
            id: 121,
            name: "角色查询",
            type: "button",
            description: "查看角色列表"
          },
          {
            id: 122,
            name: "角色新增",
            type: "button",
            description: "新增角色"
          },
          {
            id: 123,
            name: "角色修改",
            type: "button",
            description: "修改角色信息"
          },
          {
            id: 124,
            name: "角色删除",
            type: "button",
            description: "删除角色"
          },
          {
            id: 125,
            name: "权限分配",
            type: "button",
            description: "分配角色权限"
          }
        ]
      },
      {
        id: 13,
        name: "权限管理",
        icon: "ep:key",
        type: "menu",
        description: "系统权限管理",
        children: [
          {
            id: 131,
            name: "权限查询",
            type: "button",
            description: "查看权限列表"
          },
          {
            id: 132,
            name: "权限新增",
            type: "button",
            description: "新增权限"
          },
          {
            id: 133,
            name: "权限修改",
            type: "button",
            description: "修改权限信息"
          },
          { id: 134, name: "权限删除", type: "button", description: "删除权限" }
        ]
      },
      {
        id: 14,
        name: "系统设置",
        icon: "ep:tools",
        type: "menu",
        description: "系统参数配置",
        children: [
          {
            id: 141,
            name: "参数查询",
            type: "button",
            description: "查看系统参数"
          },
          {
            id: 142,
            name: "参数修改",
            type: "button",
            description: "修改系统参数"
          }
        ]
      }
    ]
  },
  {
    id: 2,
    name: "内容管理",
    icon: "ep:document",
    type: "menu",
    description: "内容信息管理",
    children: [
      {
        id: 21,
        name: "活动管理",
        icon: "ep:calendar",
        type: "menu",
        description: "活动信息管理",
        children: [
          {
            id: 211,
            name: "活动查询",
            type: "button",
            description: "查看活动列表"
          },
          {
            id: 212,
            name: "活动新增",
            type: "button",
            description: "新增活动"
          },
          {
            id: 213,
            name: "活动修改",
            type: "button",
            description: "修改活动信息"
          },
          {
            id: 214,
            name: "活动删除",
            type: "button",
            description: "删除活动"
          },
          { id: 215, name: "活动审核", type: "button", description: "审核活动" }
        ]
      },
      {
        id: 22,
        name: "赛事管理",
        icon: "ep:trophy",
        type: "menu",
        description: "赛事信息管理",
        children: [
          {
            id: 221,
            name: "赛事查询",
            type: "button",
            description: "查看赛事列表"
          },
          {
            id: 222,
            name: "赛事新增",
            type: "button",
            description: "新增赛事"
          },
          {
            id: 223,
            name: "赛事修改",
            type: "button",
            description: "修改赛事信息"
          },
          {
            id: 224,
            name: "赛事删除",
            type: "button",
            description: "删除赛事"
          },
          { id: 225, name: "赛程安排", type: "button", description: "安排赛程" }
        ]
      },
      {
        id: 23,
        name: "比赛管理",
        icon: "ep:medal",
        type: "menu",
        description: "比赛信息管理",
        children: [
          {
            id: 231,
            name: "比赛查询",
            type: "button",
            description: "查看比赛列表"
          },
          {
            id: 232,
            name: "比赛新增",
            type: "button",
            description: "新增比赛"
          },
          {
            id: 233,
            name: "比赛修改",
            type: "button",
            description: "修改比赛信息"
          },
          {
            id: 234,
            name: "比赛删除",
            type: "button",
            description: "删除比赛"
          },
          {
            id: 235,
            name: "结果录入",
            type: "button",
            description: "录入比赛结果"
          }
        ]
      },
      {
        id: 24,
        name: "资讯管理",
        icon: "ep:news",
        type: "menu",
        description: "资讯内容管理",
        children: [
          {
            id: 241,
            name: "资讯查询",
            type: "button",
            description: "查看资讯列表"
          },
          {
            id: 242,
            name: "资讯新增",
            type: "button",
            description: "新增资讯"
          },
          {
            id: 243,
            name: "资讯修改",
            type: "button",
            description: "修改资讯内容"
          },
          {
            id: 244,
            name: "资讯删除",
            type: "button",
            description: "删除资讯"
          },
          { id: 245, name: "资讯发布", type: "button", description: "发布资讯" }
        ]
      },
      {
        id: 25,
        name: "广告管理",
        icon: "ep:picture",
        type: "menu",
        description: "广告内容管理",
        children: [
          {
            id: 251,
            name: "广告查询",
            type: "button",
            description: "查看广告列表"
          },
          {
            id: 252,
            name: "广告新增",
            type: "button",
            description: "新增广告"
          },
          {
            id: 253,
            name: "广告修改",
            type: "button",
            description: "修改广告内容"
          },
          { id: 254, name: "广告删除", type: "button", description: "删除广告" }
        ]
      }
    ]
  },
  {
    id: 3,
    name: "运营管理",
    icon: "ep:data-analysis",
    type: "menu",
    description: "运营数据管理",
    children: [
      {
        id: 31,
        name: "订单管理",
        icon: "ep:shopping-cart",
        type: "menu",
        description: "订单信息管理",
        children: [
          {
            id: 311,
            name: "订单查询",
            type: "button",
            description: "查看订单列表"
          },
          {
            id: 312,
            name: "订单处理",
            type: "button",
            description: "处理订单"
          },
          { id: 313, name: "退款处理", type: "button", description: "处理退款" }
        ]
      },
      {
        id: 32,
        name: "财务管理",
        icon: "ep:money",
        type: "menu",
        description: "财务数据管理",
        children: [
          {
            id: 321,
            name: "财务查询",
            type: "button",
            description: "查看财务数据"
          },
          {
            id: 322,
            name: "财务统计",
            type: "button",
            description: "财务数据统计"
          }
        ]
      },
      {
        id: 33,
        name: "数据统计",
        icon: "ep:data-line",
        type: "menu",
        description: "运营数据统计",
        children: [
          {
            id: 331,
            name: "数据查询",
            type: "button",
            description: "查看统计数据"
          },
          {
            id: 332,
            name: "报表导出",
            type: "button",
            description: "导出统计报表"
          }
        ]
      },
      {
        id: 34,
        name: "操作日志",
        icon: "ep:document-copy",
        type: "menu",
        description: "系统操作日志",
        children: [
          {
            id: 341,
            name: "日志查询",
            type: "button",
            description: "查看操作日志"
          },
          { id: 342, name: "日志导出", type: "button", description: "导出日志" }
        ]
      }
    ]
  }
]);

// 获取权限类型文本
const getPermissionTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    menu: "菜单",
    button: "按钮",
    api: "接口"
  };
  return typeMap[type] || "未知";
};

// 展开全部
const handleExpandAll = () => {
  if (!permissionTreeRef.value) return;

  const expandKeys: number[] = [];
  const traverse = (nodes: any[]) => {
    nodes.forEach(node => {
      if (node.children && node.children.length > 0) {
        expandKeys.push(node.id);
        traverse(node.children);
      }
    });
  };

  traverse(permissionTree.value);
  permissionTreeRef.value.setExpandedKeys(expandKeys);
};

// 收起全部
const handleCollapseAll = () => {
  if (!permissionTreeRef.value) return;
  permissionTreeRef.value.setExpandedKeys([]);
};

// 全选
const handleCheckAll = () => {
  if (!permissionTreeRef.value) return;

  const allKeys: number[] = [];
  const traverse = (nodes: any[]) => {
    nodes.forEach(node => {
      allKeys.push(node.id);
      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    });
  };

  traverse(permissionTree.value);
  permissionTreeRef.value.setCheckedKeys(allKeys);
};

// 取消全选
const handleUncheckAll = () => {
  if (!permissionTreeRef.value) return;
  permissionTreeRef.value.setCheckedKeys([]);
};

// 权限选择变化
const handlePermissionCheck = () => {
  if (!permissionTreeRef.value) return;

  const checkedKeys = permissionTreeRef.value.getCheckedKeys();
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys();
  formData.permissions = [...checkedKeys, ...halfCheckedKeys] as any;
};

// 返回
const handleBack = () => {
  router.back();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (formData.permissions.length === 0) {
      ElMessage.warning("请至少选择一个权限");
      return;
    }

    submitting.value = true;

    // 这里应该调用API创建角色
    await new Promise(resolve => setTimeout(resolve, 1000));

    ElMessage.success("角色创建成功");
    router.push("/role/list");
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitting.value = false;
  }
};

onMounted(() => {
  // 初始化时展开第一级节点
  setTimeout(() => {
    if (permissionTreeRef.value) {
      const firstLevelKeys = permissionTree.value.map(item => item.id);
      permissionTreeRef.value.setExpandedKeys(firstLevelKeys);
    }
  }, 100);
});
</script>

<style scoped lang="scss">
.role-create-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.form-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.role-form {
  max-width: 1000px;
}

.form-section {
  margin-bottom: 32px;

  &:last-child {
    margin-bottom: 0;
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 20px;
    padding-bottom: 8px;
    border-bottom: 2px solid #e4e7ed;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.permission-config {
  .config-actions {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 6px;
  }

  .permission-tree {
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    padding: 12px;
    max-height: 400px;
    overflow-y: auto;

    .tree-node {
      display: flex;
      align-items: center;
      gap: 8px;
      flex: 1;

      .node-icon {
        font-size: 14px;
        color: #409eff;
      }

      .node-label {
        font-weight: 500;
      }

      .node-type {
        margin-left: 8px;
      }

      .node-desc {
        margin-left: auto;
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

@media (max-width: 768px) {
  .role-create-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .role-form {
    .el-col {
      width: 100%;
    }
  }

  .config-actions {
    flex-wrap: wrap;
  }

  .form-actions {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }
}
</style>
